import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/utils/ColorsUtil.dart';
import '../../../bean/home/HomeContentBean.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ImageHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/view/main/home/HomeVM.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/view/main/home/Recommend.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/widget/OverScrollBehavior.dart';

import 'Home.dart';

class MBannerWidget extends StatefulWidget {
  const MBannerWidget({Key? key}) : super(key: key);

  @override
  _MBannerWidgetState createState() => _MBannerWidgetState();
}

class _MBannerWidgetState extends State<MBannerWidget> {

  var list =[];

  late PageController _pageController;
  bool isGesture=false;
  late Timer timer;
  int index = 0;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: 153,keepPage: false, viewportFraction: 1)..addListener(() {
       double page = _pageController.page??0;
       onPageColorTran(page);
    });
    _autoPageChang();
  }

  //根据viewpage 的滑动值${page} 计算出过渡颜色值
  void onPageColorTran(double page) {
    int startPage=page.toInt();
    int endPage=page.toInt()+1;
    double positionOffset=page-startPage;
    var list = vm.homeBean?.advertiseList;
    var startColor = ColorsUtil.getColorFromHex(list?[startPage%list.length].color??"#ffffff");
    var endColor = ColorsUtil.getColorFromHex(list?[endPage%list.length].color??"#ffffff");
    var changeColor = ColorsUtil.getChangeColor(positionOffset, startColor, endColor);
    homeStateNotifier.value.color=changeColor;
    homeStateNotifier.notifyListeners();
  }

  //伪无限循环
  _autoPageChang(){
    timer= Timer.periodic(Duration(seconds: 3), (timer){
      _pageChang();
    });
  }

  //改变page
  _pageChang(){
    if(!isGesture){
      int nextPage=index+1;
      if(nextPage > 1000){
         nextPage=150;
      }
      if(nextPage < 100){
        nextPage=150;
      }
      _pageController.animateToPage(nextPage, duration: Duration(milliseconds: nextPage==list.length*50?1:300), curve: Interval(0, 1));
    }
  }

  @override
  void dispose() {
    super.dispose();
    timer.cancel();
    _pageController.removeListener(() { });
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.all(Radius.circular(8.r)),
      child: ChangeNotifierProvider(
        create: (_){return vm;},
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [
            //手势拦截
            Listener(
              onPointerDown: (PointerDownEvent event){
                isGesture=true;
              },
              onPointerUp: (PointerUpEvent event){
                isGesture=false;
              },
              onPointerMove: (PointerMoveEvent event){
                isGesture=true;
              },
              onPointerCancel: (PointerCancelEvent event){
                isGesture=false;
              },
              child: PageView.builder(
                controller: _pageController,
                onPageChanged: (value){
                  setState(() {
                    index = value;
                  });
                },
                scrollBehavior: OverScrollBehavior(),
                dragStartBehavior: DragStartBehavior.start,
                itemCount: 1100,
                itemBuilder: (BuildContext context, int index) {
                  return TextButton(
                    style: ButtonStyle(padding:MaterialStateProperty.all(EdgeInsets.zero)),
                    onPressed: (){
                       print("事件点击 $index");
                    },
                    child: ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(8.r)),
                      child: Selector(
                        builder: (context,List<AdvertiseList>? list, _){
                          if(list==null || list.length==0) return Text("");
                          this.list=list;
                          return assetImage(
                               list[index % list.length].pic??"",
                               width: double.infinity,
                               height: double.infinity,
                               fit: BoxFit.cover);
                        },
                        selector:(_, HomeVM vm){
                           return vm.homeBean?.advertiseList;
                        }
                      ),
                    ),
                  );
                },
              ),
            ),
          LocationWidget(list.length,index)
          ],
        ),
      ),
    );
  }
}

class LocationWidget extends StatefulWidget {
  late int size;
  late int _index = 0;

  LocationWidget(this.size, int index){
    if(size==0){
      _index=0;
    }else{
      _index=index%size;
    }
  }

  @override
  _LocationWidgetState createState() =>  _LocationWidgetState();
}

class _LocationWidgetState extends State<LocationWidget> {

  @override
  Widget build(BuildContext context) {
    return Positioned(
      bottom: 8.h,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: List.generate(widget.size, (index) {
          return Container(
            alignment: Alignment.bottomCenter,
            width: widget._index == index ? 8.w : 3.w,
            height: 3.w,
            margin: EdgeInsets.fromLTRB(3.w, 3.w, 3.w, 5.w),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(3.r),
                color: Color(widget._index == index ? 0xffffffff : 0x88ffffff)),
          );
        }),
      ),
    );
  }
}

